#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tmf_dataflow.py 
@version:
@time: 2022/01/06 
"""
from TapClientCore.T02_tm_api.v1_api.v1_tm import V1DataFlows

from TapUtil.decorator.some_useful import timeout
from TapUtil.logfunc.logger import logger


class TMFV1DataFlow:
    def __init__(self, change=''):
        self.v1tm = V1DataFlows(change)

    # 创建
    def _create_dataflows(self, payload):
        return self.v1tm.post_dataflows(payload)

    #  删除
    def _delete_dataflow(self, _id):
        where = {"_id": {"inq": [_id]}}
        return self.v1tm.post_dataflows_removeall(where)

    # 查询
    def _query_dataflow_by_filter(self, _filter):
        return self.v1tm.get_dataflows_by_filter(_filter).get('data')

    # 查询 by id
    def _query_dataflow_by_id(self, _id):
        if _id:
            return self.v1tm.get_dataflows_by_id(_id).get('data')
        else:
            logger.fatal('not found dataflow')

    # 更新dataflow
    def _patch_dataflow(self, payload):
        return self.v1tm.patch_dataflows(payload)

    # 启动
    def _update_dataflow_by_id(self, _id, payload):
        where = {"_id": {"in": [_id]}}
        return self.v1tm.post_dataflows_update(where, payload)

    # query id by name
    def query_dataflow_some_by_name(self,
                                    name,
                                    fields=None,
                                    get='id'
                                    ):
        if not fields:
            fields = {}
        fields.update({"id": True, "name": True})
        where = {"mappingTemplate": "cluster-clone"}
        limit = 20
        skip = 0
        while True:
            _filter = {
                "order": "createTime DESC",
                "limit": limit,
                "fields": fields,
                "skip": skip,
                "where": where}
            response = self._query_dataflow_by_filter(_filter)
            if response:
                for one in response:
                    if one.get('name') == name:
                        return one.get(get)
            else:
                break
            skip += limit
        where = {"mappingTemplate": "custom"}
        limit = 20
        skip = 0
        while True:
            _filter = {
                "order": "createTime DESC",
                "limit": limit,
                "fields": fields,
                "skip": skip,
                "where": where}
            response = self._query_dataflow_by_filter(_filter)
            if response:
                for one in response:
                    if one.get('name') == name:
                        return one.get(get)
            else:
                break
            skip += limit

    # query by name
    def query_dataflow_by_name(self, name):
        _id = self.query_dataflow_some_by_name(name)
        return self._query_dataflow_by_id(_id)

    # wait to running
    @timeout('running', 24)
    def _wait_dataflow_running(self, name):
        status = self.query_dataflow_some_by_name(
            name,
            {'status': True},
            'status'
        )
        if status == 'error':
            raise f'dataflow error'
        return status

    # wait to paused
    @timeout('paused', 24)
    def _wait_dataflow_paused(self, name):
        status = self.query_dataflow_some_by_name(
            name,
            {'status': True},
            'status'
        )
        if status == 'error':
            raise f'dataflow error'
        return status

    # start
    def _start_dataflow_by_name(self, name):
        _id = self.query_dataflow_some_by_name(name)
        payload = {"status": "scheduled"}
        return self._update_dataflow_by_id(_id, payload)

    # stop
    def _stopping_dataflow_by_name(self, name):
        _id = self.query_dataflow_some_by_name(name)
        payload = {"status": "stopping"}
        return self._update_dataflow_by_id(_id, payload)

    def start_and_wait_to_running(self, name):
        self._start_dataflow_by_name(name)
        self._wait_dataflow_running(name)

    def stopping_and_wait_to_paused(self, name):
        self._stopping_dataflow_by_name(name)
        self._wait_dataflow_paused(name)

    def start_and_wait_to_paused(self, name):
        self._start_dataflow_by_name(name)
        self._wait_dataflow_paused(name)

    # delete
    def delete_dataflow_by_name(self, name):
        _id = self.query_dataflow_some_by_name(name)
        logger.info(f'{name}: {_id} is delete')
        return self._delete_dataflow(_id)

    # reset
    def reset_dataflow_by_name(self, name):
        _id = self.query_dataflow_some_by_name(name)
        return self.v1tm.post_dataflows_reset_by_id(_id)

    # create
    def create_dataflow(self, payload):
        return self._create_dataflows(payload)

    # patch
    def patch_dataflow(self, payload):
        return self._patch_dataflow(payload)


if __name__ == '__main__':
    T = TMFV1DataFlow()
    T.start_and_wait_to_running('test1')
